﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml;
using Baggr.FeedParser;
using FeedReader;

namespace Baggr.Agent
{
    public class FeedReaderTask
    {
        private readonly Feed _Feed;
        private readonly WebRequest _Request;

        public FeedReaderTask(Feed feed)
        {
            if (feed == null)
                throw new ArgumentNullException("feed");
            _Feed = feed;
            _Request = WebRequest.Create(feed.Link);
            _Request.BeginGetResponse(OnProcess, null);
        }

        private void OnProcess(IAsyncResult result)
        {
            if (!result.IsCompleted)
                return;
            Stream stream = _Request.EndGetResponse(result).GetResponseStream();
            XmlReader reader = XmlReader.Create(stream);
            var newFeeds = reader.GetFeed().Items.Where(curr => _Feed.Items.FirstOrDefault(exists => exists.LocalId != curr.LocalId) == null);
            foreach(var feed in newFeeds)
            {
                var newFeed = new FeedItem()
                                  {
                                      Author = feed.Author,
                                      Date = feed.PublicationDate,
                                      Description = feed.Description,
                                      Feed = _Feed,
                                      Link = feed.Link.ToString(),
                                      LocalId = feed.LocalId,
                                      Title = feed.Title
                                  };
                _Feed.Items.Add(newFeed);
            }
        }
    }
}
